//
//  SSOAthViewController.swift
//  MyMicroBlog
//
//  Created by stevenSu on 15/7/29.
//  Copyright © 2015年 stevenSu. All rights reserved.
//

import UIKit
import SVProgressHUD

private let showErrorDuration: UInt64 = 1
class SSOAuthViewController: UIViewController, UIWebViewDelegate {

    lazy private var webView: UIWebView = {
       let view = UIWebView()
        view.delegate = self
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        view = webView
        webView.loadRequest(NSURLRequest(URL: SSNetworkTools.sharedNetworkTools.oauthURL))
        
    }
    
    // MARK: - UIWebViewDelegate
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 取消授权
        if let query = request.URL?.query where query.hasPrefix("error"){
            close()
            return false
        }
        // 点击授权
        if let query = request.URL?.query where query.hasPrefix("code="){
            print("点击授权")
            let code = query.substringFromIndex(advance("code=".endIndex, 0))
            loadAccessToken(code)
            return false
        }
        
        return true
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 获取token
    ///
    /// - parameter code: 授权码
    private func loadAccessToken(code: String) {
        SSNetworkTools.sharedNetworkTools.loadAccessToken(code, completion: { (token, error) -> () in
            if error != nil || token == nil {
                SVProgressHUD.showErrorWithStatus("网络不给力啊！")
                let time = dispatch_time(DISPATCH_TIME_NOW, Int64(showErrorDuration * NSEC_PER_SEC))
                dispatch_after(time, dispatch_get_main_queue(), { () -> Void in
                    self.close()
                })
                return
            }
            
            let userToken = SSUserToken(dict: token!)
            print("userToken---\(userToken)")
            userToken.saveToken()
            NSNotificationCenter.defaultCenter().postNotificationName(SSRootControllerSwitchNotification, object: false)
            self.close()
        })
    }

}
